﻿// 对图像进行常见的平滑滤波处理
//

#include "pch.h"
#include <string>
#include <iostream>
#include <opencv2/opencv.hpp>
#include "saltPepper.h"

using namespace std;
using namespace cv;

		
//盐噪声
void salt(cv::Mat image, int n)
{

	int i, j;
	for (int k = 0; k < n / 2; k++)
	{
		// rand() is the random number generator		
		i = std::rand() % image.cols; // % 整除取余数运算符,rand=1022,cols=1000,rand%cols=22		
		j = std::rand() % image.rows;
		if (image.type() == CV_8UC1)
		{
			// gray-level image 			
			image.at<uchar>(j, i) = 255;
			//at方法需要指定Mat变量返回值类型,如uchar等 		
		}
		else if (image.type() == CV_8UC3)
		{ // color image 			
			image.at<cv::Vec3b>(j, i)[0] = 255; //cv::Vec3b为opencv定义的一个3个值的向量类型			
			image.at<cv::Vec3b>(j, i)[1] = 255; //[]指定通道，B:0，G:1，R:2			
			image.at<cv::Vec3b>(j, i)[2] = 255;
		}
	}
}
//椒噪声
void pepper(cv::Mat image, int n)
{
	int i, j;
	for (int k = 0; k < n; k++)
	{
		// rand() is the random number generator		
		i = std::rand() % image.cols; // % 整除取余数运算符,rand=1022,cols=1000,rand%cols=22		
		j = std::rand() % image.rows;
		if (image.type() == CV_8UC1)
		{
			// gray-level image 			
			image.at<uchar>(j, i) = 0;
			//at方法需要指定Mat变量返回值类型,如uchar等 		
		}
		else if (image.type() == CV_8UC3)
		{ // color image 			
			image.at<cv::Vec3b>(j, i)[0] = 0; //cv::Vec3b为opencv定义的一个3个值的向量类型			
			image.at<cv::Vec3b>(j, i)[1] = 0; //[]指定通道，B:0，G:1，R:2			
			image.at<cv::Vec3b>(j, i)[2] = 0;
		}
	}
}

int main()
{
	Mat image = imread("E:\\VC_project\\figure\\lena.jpg");

	Mat image1, imageBlur, imageGaussianBlur, imageMedianBlur,imageSaltPepper;

	pyrDown(image, image1);
	image1.copyTo(imageSaltPepper);

	//对图像进行平均滤波
	blur(image1, imageBlur, Size(3, 3));
	imshow("原始图像", image1);
	imshow("平均滤波", imageBlur);

	//对图像进行高斯平滑滤波
    GaussianBlur(image1, imageGaussianBlur, Size(3, 3), 0);
	imshow("高斯平滑滤波", imageGaussianBlur);

	//对图像进行中值滤波处理
	medianBlur(image1, imageMedianBlur, 3);
	imshow("中值滤波", imageGaussianBlur);

	//加入椒盐噪声后进行中值滤波处理
	salt(imageSaltPepper, 500);
    pepper(imageSaltPepper,500);
	medianBlur(imageSaltPepper, imageMedianBlur, 3);
	imshow("椒盐噪声", imageSaltPepper);
	imshow("加入椒盐噪声后中值滤波", imageMedianBlur);

	Mat element = getStructuringElement(MORPH_RECT, Size(3, 3));
	Mat imgEx;
	morphologyEx(image, imgEx, MORPH_OPEN, element); //开运算
	morphologyEx(imgEx, imgEx, MORPH_CLOSE, element);
	imshow("形态学滤波", imgEx);


	waitKey();
}

